package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioConstantProperties minioConstantProperties;
    @Override
    @SneakyThrows
    public String fileUpload(MultipartFile file) {

        //构建minioClient
        MinioClient minioClient =
          MinioClient.builder()
              .endpoint(minioConstantProperties.getEndpointUrl())
              .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
              .build();

        //判断有没有桶，没有则创建
         boolean found =
          minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
      if (!found) {
        // 没有就创建.
        minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
      }

      //上传文件

        String uuid = UUID.randomUUID().toString().replace("-", "");
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String objectName = uuid +"."+ substring;

        //获取文件输入流
        InputStream inputStream = file.getInputStream();

        PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName())
                .object(objectName)
                .stream(inputStream, file.getSize(), -1).build();
        minioClient.putObject(putObjectArgs);

        //返回文件地址
        String url = minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+objectName;

        return url;
    }
}
